import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  tabList: [{ key: '/dashboard', label: '首页' }],
  activeTab: '/dashboard'
}

const tabsSlice = createSlice({
  name: 'tabs',
  initialState,
  reducers: {
    // 新增tab
    addTab: (state, action) => {
      const { key } = action.payload
      if (state.tabList.some((tab) => tab.key === key)) {
        state.activeTab = key
        return
      }
      state.tabList.push(action.payload)
    },
    // 删除tab
    removeTab: (state, action) => {
      state.tabList = state.tabList.filter((tab) => tab.key !== action.payload)
      if (state.activeTab === action.payload) {
        state.activeTab = state.tabList.length
          ? state.tabList[state.tabList.length - 1].key
          : '/dashboard'
      }
    },
    setActiveTab: (state, action) => {
      state.activeTab = action.payload
    }
  }
})

export const { setTabsList, setActiveTab, removeTab, addTab } =
  tabsSlice.actions
export default tabsSlice.reducer
